package logger

import (
	"context"
	"io"
	"log/slog"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

var logDir = time.Now().Format("2006-01-02-15-04-05")
var level int
var logPath string

const DtLoggingPathKey = "DT_LOGGING_PATH"
const DtLoggingLevelKey = "DT_LOGGING_LEVEL"

var logLevels = []slog.Level{100, slog.LevelError, slog.LevelWarn, slog.LevelInfo, slog.LevelDebug}

func init() {

	logPath = os.Getenv(DtLoggingPathKey)
	if len(logPath) == 0 {
		logPath = "./log"
	}
	levelStr := os.Getenv(DtLoggingLevelKey)
	if len(levelStr) == 0 {
		levelStr = "3"
	}

	info, e := os.Stat(logPath)

	if e != nil {
		//尝试创建
		e := os.Mkdir(logPath, os.ModePerm)
		if e != nil {
			panic(e)
		} else {
			info, e = os.Stat(logPath)
			if e != nil {
				panic(e)
			}
		}
	}
	if !info.IsDir() {
		panic(logPath + " is not a directory")
	}

	e = os.Mkdir(filepath.Join(logPath, logDir), os.ModePerm)
	if e != nil {
		panic(e)
	}
	_level, e := strconv.Atoi(levelStr)
	if e != nil {
		panic(e)
	}
	level = _level
}
func NewLogger(loggerName string) *slog.Logger {

	if level < 0 || level > 4 {
		panic("invalid log level")
	}
	var w io.Writer
	if len(logPath) != 0 {
		info, e := os.Stat(logPath)
		if e != nil {
			panic(e)
		}
		if !info.IsDir() {
			panic(logPath + " is not a directory")
		}
		f, err := os.Create(filepath.Join(logPath, logDir, loggerName+".log"))
		if err != nil {
			panic(err)
		}
		w = io.MultiWriter(os.Stdout, f)
	} else {
		w = os.Stdout
	}
	logger := slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{Level: logLevels[level]})).With("logger", loggerName)
	return logger
}

type disabledHandler struct{}

func (disabledHandler) Enabled(context.Context, slog.Level) bool { return false }
func (disabledHandler) Handle(context.Context, slog.Record) error {
	return nil
}

func (disabledHandler) WithAttrs([]slog.Attr) slog.Handler {
	return nil
}

func (disabledHandler) WithGroup(string) slog.Handler {
	return nil
}
